<template>
  <view class="content addressInfoContent">
    <view style="width: 100vw; height: 30rpx"></view>
    <view style="padding: 30rpx; background-color: #fff">
      <view style="background-color: #f0f0f0;border-radius: 8rpx; display: flex; flex-direction: column; padding: 30rpx;">
        <up-textarea
            v-model="recognize"
            border="none"
            placeholderStyle="font-size: 28rpx;"
            :maxlength="-1"
            autoHeight
            height="96"
            confirm-type="return"
            :confirm-hold="true"
            customStyle="padding: 8rpx 24rpx; background-color: #f0f0f0;min-height: 96rpx;"
            placeholder="请粘贴或输入文本，点击“粘贴并识别”自动识别收获人、手机号、地址"></up-textarea>
        <view style="display: flex; flex-direction: row; align-items: center; justify-content: flex-end; margin-top: 24rpx">
          <view
            v-if="recognize?.length"
            class="recognizeBtn"
            @click="() => recognize = ''">
            清空
          </view>
          <view
            :style="{
              opacity: recognize?.length ? 1 : 0.6,
            }"
            class="recognizeBtn"
            style="background-color:#79C435; color: #fff; margin-left: 16rpx;"
            @click="recognizeMsg">
            粘贴并识别
          </view>
        </view>
      </view>
    </view>
    <up-form :model="detail" ref="form1" labelPosition="left">
      <view style="background-color: #fff; padding: 0 30rpx;">
        <up-form-item label="收货人" prop="name" borderBottom ref="item1" labelWidth="180rpx" labelPosition="left">
          <template v-slot:label>
            <view class="formItemLeft">
              <up-text text="收货人" color="#303133" type="" size="28"></up-text>
            </view>
          </template>
          <up-input v-model="detail.name" :customStyle="inputStyle" border="none" fontSize="28" placeholder="请输入收货人姓名"></up-input>
        </up-form-item>
        <up-form-item label="手机号" prop="phone" borderBottom ref="item2" labelWidth="180rpx" labelPosition="left">
          <template v-slot:label>
            <view class="formItemLeft">
              <up-text text="手机号" color="#303133" type="" size="28"></up-text>
            </view>
          </template>
          <up-input v-model="detail.phone" :customStyle="inputStyle" border="none" fontSize="28" placeholder="请输入收货人手机号"></up-input>
        </up-form-item>
        <up-form-item label="所在地区" prop="province" borderBottom ref="item3" labelWidth="180rpx" labelPosition="left">
          <view @click="show = true">
            <up-text lineHeight="48" type="" color="#999999" size="28" v-if="!detail?.province.length" text="请选择省/市/区"></up-text>
            <up-text v-else lineHeight="48" type="main" size="28" :text="`${detail.province} ${detail.city} ${detail.area}`"></up-text>
          </view>
        </up-form-item>
        <up-form-item label="详细地址" prop="addr" borderBottom ref="item4" labelWidth="180rpx" labelPosition="left">
          <template v-slot:label>
            <view class="formItemLeft">
              <up-text text="详细地址" color="#303133" type="" size="28"></up-text>
            </view>
          </template>
          <up-textarea
            v-model="detail.addr"
            border="none"
            placeholderStyle="font-size: 28rpx;"
            height="96"
            :maxlength="-1"
            customStyle="padding: 8rpx 0;"
            placeholder="请输入详细地址"></up-textarea>
        </up-form-item>
      </view>
      <view style="margin-top: 30rpx; background-color: #fff; padding: 0 30rpx;">
        <up-form-item label="设为默认" prop="isDefault" ref="item5" labelPosition="left" labelWidth="180rpx">
          <template v-slot:label>
            <view class="formItemLeft" style="width: 300rpx;">
              <up-text text="设置为默认地址" color="#303133" type="" size="28" ></up-text>
            </view>
          </template>
          <view class="itemRight">
            <up-switch v-model="detail.isDefault" @change="changeIsDefault" size="68" activeColor="#79C435"></up-switch>
          </view>
        </up-form-item>
      </view>
    </up-form>
    <view v-if="isEdit" class="deleteWrap row" @click="deleteItem">
      <up-text align="center" lineHeight="88" size="28" type="" color="#333" text="删除地址"></up-text>
    </view>
    <view class="bottomView"></view>
    <view class="bottomWrap" @click="saveAddress">
      <up-text type="" color="#fff" :text="isEdit ? '保存并更新' : '保存'" align="center" size="28"></up-text>
    </view>
    <up-picker :show="show" ref="uPickerRef" :columns="columns" @confirm="confirm" @change="changeHandler"
      @cancel="show=false" confirmColor="#79C435" itemHeight="68"></up-picker>
  </view>
</template>

<script>
import pca from '@/static/pca.json';
import { deleteAddress, addOrUpdateAddress, matchAddressInfo } from '@/services/address';

export default {
  onLoad(options) {
    const _that = this;
    const { isEdit } = options || {};
    
    const list = Object.keys(pca);
    const cityList = Object.keys(pca[list[0]]);
    const areaList = pca[list[0]][cityList[0]];
    this.columns = [list, cityList, areaList];
    this.provinceList = list;
    this.cityList = cityList;
    this.areaList = areaList;

    this.isEdit = isEdit;
    // @ts-ignore
    uni.setNavigationBarTitle({ title: isEdit ? '编辑地址' : '添加收获地址' });
    const eventChannel = this.getOpenerEventChannel();
    eventChannel?.on('addressDetail', ({ data }) => {
      const { detail, ...other } = data || {};
      _that.detail = {
        ...other,
        addr: detail,
        isDefault: `${data.isDefault}` === '1'
      };
      _that.setPickerIndex([data.province, data.city, data.area]);
    });
  },
  data() {
    return {
      show: false,
      isEdit: false,
      recognize: '',
      timer: 0,
      inputStyle: {
        height: '48rpx'
      },
      columns: [],
      provinceList: [],
      cityList: [],
      areaList: [],
      detail: {
        name: '',
        phone: '',
        province: '',
        city: '',
        area: '',
        addr: '',
        isDefault: false
      },
      rules: {
        'name': {
          type: 'string',
          required: true,
          message: '请输入收货人姓名',
          trigger: ['blur', 'change']
        },
        'phone': [
          {
            required: true,
            message: '请输入收货人手机号',
            trigger: ['change', 'blur'],
          },
          {
            validator: (rule, value, callback) => {
              // @ts-ignore
              return uni.$u.test.mobile(value);
            },
            message: '手机号码不正确',
            // 触发器可以同时用blur和change
            trigger: ['change', 'blur'],
          }
        ],
        'province': {
          type: 'string',
          required: true,
          message: '请选择省/市/区',
          trigger: ['change']
        },
        'addr': {
          type: 'string',
          required: true,
          message: '请输入详细地址',
          trigger: ['blur', 'change']
        },
      },
    };
  },
  onShow() {
    this.$refs.form1.setRules(this.rules);
  },
  beforeUnmount() {
    this.timer && clearTimeout(this.timer);
  },
  methods: {
    recognizeMsg() {
      const { recognize } = this;
      const _that = this;
      if (recognize) {
        matchAddressInfo({
          addr: recognize,
        }).then((res) => {
          const {success, data} = res || {};
          if (success) {
            const {province, city, area, detail, name, phone} = data || {};
            if (province && city && area && detail) {
              _that.detail = {
                ..._that.detail,
                addr: detail,
                province,
                city,
                area,
                name: name || '',
                phone: phone || '',
              };
              _that.setPickerIndex([province, city, area]);
            } else {
              uni.$u.toast('抱歉，没有识别成功');
            }
          } else {
            uni.$u.toast('抱歉，没有识别成功');
          }
        }).finally(() => {
          this.$refs.form1.validateField('province');
        })
      }
    },
    setPickerIndex (value) {
      const { provinceList } = this;
      const [province, city, area] = value || [];
      const cityList = Object.keys(pca[province]) || [];
      const areaList = pca[province][city] || [];
      this.cityList = cityList;
      this.areaList = areaList;
      this.$refs.uPickerRef.setColumnValues(0, Object.keys(pca));
      this.$refs.uPickerRef.setColumnValues(1, cityList);
      this.$refs.uPickerRef.setColumnValues(2, areaList);
      const first = Math.max(provinceList?.findIndex(item => item === province), 0);
      const second = Math.max(cityList.findIndex(item => item === city), 0);
      const third = Math.max(areaList.findIndex(item => item === area), 0);
      this.$refs.uPickerRef.setIndexs([first, second, third]);
    },
    changeHandler(e) {
      const {
        columnIndex,
        value,
        index
      } = e;
      console.log('changeHandler', e);
      const [province, city] = value || [];
      // 当第一列值发生变化时，变化第二列(后一列)对应的选项
      if (columnIndex === 0) {
        // picker为选择器this实例，变化第二列对应的选项
        const cityList = Object.keys(pca?.[province]) || [];
        const areaList = pca[province]?.[cityList[0]];
        this.cityList = cityList || [];
        this.areaList = areaList || [];
        this.$refs.uPickerRef.setColumnValues(1, cityList);
        this.$refs.uPickerRef.setColumnValues(2, areaList);
      } else if (columnIndex === 1) {
        const areaList = pca?.[province]?.[city]
        this.areaList = areaList || [];
        this.$refs.uPickerRef.setColumnValues(2, areaList);
      }
    },
    confirm(e) {
      const { value } = e || {};
      console.log('confirm', value)
      const [province, city, area] = value || [];
      this.detail.province = province;
      this.detail.city = city;
      this.detail.area = area;
      this.$refs.form1.validateField('province');
      this.show = false
    },
    changeIsDefault(e) {
      this.detail.isDefault = e;
    },
    saveAddress() {
      const _that = this;
      const { isEdit, detail } = this;
      this.$refs.form1.validate().then(async (res) => {
        let result;
        if (!res) return;
        const { province, city, area, addr, ...other } = detail || {};
        result = await addOrUpdateAddress({
          addr: `${province}${city}${area}${addr}`,
          ...other,
          isDefault: detail.isDefault ? "1" : "2",
        });
        if (result?.success) {
          uni.$u.toast(isEdit ? '编辑成功' : '收货地址新增成功');
          _that.timer = setTimeout(() => {
            uni.navigateBack();
          }, 1500)
        } else {
          uni.$u.toast(result.msg || '收货地址新增失败！');
        }
      })
    },
    async deleteItem() {
      const _that = this;
      const { id } = this.detail;
      uni.showModal({
        title: '是否删除当前地址',
        confirmText: '删除',
        cancelText: '取消',
        success: async (res) => {
          if (res.confirm) {
            const v = await deleteAddress({id});
            if (v?.success) {
              const eventChannel = _that.getOpenerEventChannel();
              eventChannel?.emit('deleteAddress', id);
              _that.timer = setTimeout(() => {
                uni.navigateBack();
              }, 1500)
              uni.$u.toast('删除成功！')
            } else {
              uni.$u.toast('删除失败！')
            }
          }
        }
      })
    }
  },
};
</script>

<style>
.addressInfoContent input {
  /* padding-top: 32rpx; */
  padding: 8rpx 0;
}
.addressInfoContent textarea {
  padding: 4rpx 0;
  font-size: 28rpx !important;
  color: #333;
}
</style>

<style lang="scss" scoped>
.formItemLeft {
  width: 180rpx;
  padding: 8rpx 0;
}
.content{
  width: 100vw;
  min-height: 100vh;
  background-color: #f8f8f8;
}
.itemRight{
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
  align-items: center;
}
.bottomWrap{
  position: fixed;
  bottom: 0;
  left: -2vw;
  width: 104vw;
  height: 88rpx;
  display: flex;
  justify-content: center;
  margin-bottom: constant(safe-area-inset-bottom);
	margin-bottom: env(safe-area-inset-bottom);
  background-image: url('../../static/login.png');
  background-size: cover;
  background-position: center center;
}
.bottomView {
  width: 100vw;
  height: 88rpx;
  margin-bottom: constant(safe-area-inset-bottom);
	margin-bottom: env(safe-area-inset-bottom);
}
.deleteWrap{
  justify-content: center;
  margin-top: 30rpx;
  padding: 0 30rpx;
  height: 88rpx;
  background-color: #fff;
}
.inputClass {
  font-weight: bolder;
}
.recognizeBtn {
  color: #666;
  font-size: 28rpx;
  height: 64rpx;
  border-radius: 32rpx;
  padding: 0 8rpx;
  line-height: 64rpx;
}
</style>
